package com.shc.xsocket.demo1;

import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.NonBlockingConnection;

import java.io.IOException;
import java.nio.channels.Selector;

/**
 * Created by shihuacai on 2015/12/31.
 */
public class XSocketClient {
    private static final int PORT = 8014;

    public static void main(String[] args) throws IOException {
        //采用非阻塞式的连接
        INonBlockingConnection nbc = new NonBlockingConnection("localhost", PORT, new ClientHandler());

        //采用阻塞式的连接
        //IBlockingConnection bc = new BlockingConnection("localhost", PORT);
        //一个非阻塞的连接是很容易就变成一个阻塞连接
        IBlockingConnection bc = new BlockingConnection(nbc);
        //设置编码格式
        bc.setEncoding("UTF-8");
        //设置是否自动清空缓存
        bc.setAutoflush(true);
        //向服务端写数据信息
        for (int i = 0; i < 100; i++) {
            bc.write(" client " + i + " love china !...|");
        }
        //向客户端读取数据的信息
        byte[] byteBuffers = bc.readBytesByDelimiter("|", "UTF-8");
        //打印服务器端信息
        System.out.println(new String(byteBuffers));
        //将信息清除缓存，写入服务器端
        bc.flush();
        bc.close();
        Thread t =  new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){}
            }
        });
        t.setDaemon(false);
        t.start();
    }

}
